package com.mmd.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CheckUtil {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CheckUtil.class);
	
	private static final String token = "trueme";

	public static String getSignature(String noncestr, String jsapi_ticket, String timestamp, String url) {
		noncestr = "noncestr=" + noncestr;
		jsapi_ticket = "jsapi_ticket=" + jsapi_ticket;
		timestamp = "timestamp=" + timestamp;
		url = "url=" + url;
		String[] arr = new String[] { noncestr, jsapi_ticket, url, timestamp };
		// 排序
		Arrays.sort(arr);

		// 组装
		StringBuffer content = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			if (i != arr.length - 1) {
				content.append(arr[i] + "&");
			} else {
				content.append(arr[i]);
			}
		}
		// sha1加密
		String temp = SHA1(content.toString());
		return temp;
	}

	public static boolean checkSignature(String signature, String timestamp, String nonce) {
		String[] arr = new String[] { token, timestamp, nonce };
		// 排序
		Arrays.sort(arr);

		// 组装
		StringBuffer content = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		// sha1加密
		String temp = SHA1(content.toString());
		return temp.equals(signature);
	}

	public static String SHA1(String decript) {
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
			digest.update(decript.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			LOGGER.error("NoSuchAlgorithmException", e);
		}
		return "";
	}
}
